package com.hongsheng.listener;

import com.hongsheng.mapper.DepositoryMapper;
import com.hongsheng.mapper.DriverMapper;
import com.hongsheng.mapper.OrderMapper;
import com.hongsheng.pojo.Depository;
import com.hongsheng.pojo.Driver;
import com.hongsheng.pojo.Order;
import com.hongsheng.util.NewGetDistance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DatabasePoller {

    @Autowired
    private DriverMapper driverMapper; // 替换为实际的数据库操作类
    @Autowired
    private DepositoryMapper depositoryMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(fixedDelay = 10000) // 10秒钟执行一次
    public void pollDatabase() {
        List<Driver> allDriver = driverMapper.findFreeDriver();
        for (Driver driver : allDriver) {
            if (driver.getStatus()!=null && driver.getStatus()==0 && driver.getAddress()!=null && !driver.getAddress().isEmpty()){
                List<String> strings = orderMapper.AllAddress();
                String shortestDepositoryAddress = null;
                double shortestDistance = Double.MAX_VALUE;
                for (String address : strings) {
                    Double distance = NewGetDistance.distance(driver.getAddress(), address);
                    if (distance < shortestDistance) {
                        shortestDistance = distance;
                        shortestDepositoryAddress = address;
                    }
                }
                driver.setAddress(shortestDepositoryAddress);
                if (shortestDepositoryAddress != null) {
                   driverMapper.updateDriver(driver);
                }
            }
        }
        // 执行数据库查询，检查字段的值是否为0
        // 如果是，执行业务逻辑
        // 例如：yourRepository.checkAndPerformLogic();
    }
}